﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Atmk.WaterMeter.MIS.Commons;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic
{
    /// <summary>
    ///     账户管理逻辑
    /// </summary>
    public class AccountManageLogic : BaseLogic, IAccountManageLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IAccountRepository _accountRepository;
        private readonly IBaseInfoLogic _baseInfoLogic;
        private readonly IDistrictRepository _districtRepository;
        private readonly IMeterRepository _meterRepository;
        private readonly IOwnerRepository _ownerRepository;
        private readonly IRefillRepository _refillRepository;
        private readonly IRepository _repository;


        public AccountManageLogic(
            IRepository repository,
            IDistrictRepository districtRepository,
            IAccountRepository accountRepository,
            IOwnerRepository ownerRepository,
            IMeterRepository meterRepository,
            IRefillRepository refillRepository,
            IBaseInfoLogic baseInfoLogic
        )
        {
            _repository = repository;
            _districtRepository = districtRepository;
            _accountRepository = accountRepository;
            _ownerRepository = ownerRepository;
            _meterRepository = meterRepository;
            _refillRepository = refillRepository;
            _baseInfoLogic = baseInfoLogic;
        }

        /// <summary>
        ///     查询账户信息
        /// </summary>
        /// <param name="token">Token</param>
        /// <param name="aid">片区Id</param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        public object SelectAccount(string areaId, string aid, int page, int pageSize, out int count,
            string searchType = "", string searchValue = "")
        {
            try
            {

                ////第一步 获取所有用户信息
                ////var districtlist = _districtRepository.FindAllAsNoTracking<DistrictEntity>().ToList();
                //var districtlist = _districtRepository.GetBaseDistrictEntities(areaId, aid);
                ////获取主区域及下所有子区域信息
                ////var districts = _districtLogic.GetDistrictsByUid(payloadId, districtlist);

                ////if (districts.Count == 0)
                ////    districts = districtlist.Where(d => d.Id.ToString() == aid).ToList();
                ////获取业主信息
                //var owners = _ownerRepository.FindAllAsNoTracking<Owner>().Where(
                //    o => districtlist.Select(d => d.Id.ToString()).Contains(o.DistrictId) &&
                //         o.RecordState == (int)RecordStateEnum.Normal).ToList();
                ////条件筛选
                //owners = _baseInfoLogic.QuerySearchOwner(searchType, searchValue, owners);
                ////获取水表信息--暂时不用，如果是按水表计费收费再用
                ////var meters = _meterRepository.FindAllAsNoTracking<Meter>().Where(
                ////    m => owners.Select(o => o.Id.ToString()).Contains(m.OwnerId) &&
                ////         m.RecordState == RecordStateEnum.Normal).ToList();
                ////meters = _baseInfoLogic.QuerySearchMeter(searchType, searchValue, meters);
                //count = owners.Count;
                //var result = new object[count];
                //for (var i = 0; i < owners.Count; i++)
                //{
                //    var owner = owners[i];
                //    var district = districtlist.First(d => owner.DistrictId.Contains(d.Id.ToString()));

                //    var accountId = ""; //账户id
                //    var balance = 0.00m; //账户余额
                //    var arrears = 0.00m;
                //    var accounts = _accountRepository.FindAllAsNoTracking<Account>()
                //        .Where(a => a.OwnerId == owner.Id.ToString()).ToList();
                //    if (accounts.Count > 0)
                //    {
                //        var account = accounts.First();
                //        accountId = account.Id.ToString();
                //        balance = account.Balance;
                //        arrears = account.Arrears;
                //    }

                //    result[i] = new
                //    {
                //        districtId = district.Id, //片区Id
                //        districtName = district.Name, //片区名称
                //        ownerId = owner.Id, //业主Id                
                //        ownerName = owner.Name, //业主名称
                //        houseNumber = owner.HouseNumber, //门牌号           
                //        mobile = owner.Mobile, //手机号码
                //        accountId, //账户id
                //        balance, //账户余额
                //        arrears
                //    };
                //}

                ////获取分页数据
                //var pageList = PaginatedList<object>.Create(result.ToList(), page, pageSize);
                //return pageList;
                //临时增加
                count = 0;
                return new object();
            }
            catch (Exception e)
            {
                throw new Exception($"查询账户信息错误{e.Message}");
            }
        }

        /// <summary>
        ///     充值
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="accountId"></param>
        /// <param name="payment"></param>
        /// <param name="lastBalance"></param>
        /// <param name="refill"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool RechargeAccount(string staffId, string staffName, string ownerId, string accountId, decimal payment, decimal lastBalance, decimal refill, out Exception exception)
        {
            //解析成功--mock
            exception = null;
            try
            {
            //    if (payment > refill)
            //    {
            //        exception = new Exception("实收金额小于应付金额,无法提交");
            //        return false;
            //    }

            //        var owner = _repository.FindAll<Owner>().First(o => o.Id.ToString() == ownerId);
            //    if (accountId == "")
            //    {
            //        //开户
            //        var ac = new Account(owner.Name)
            //        {
            //            OwnerId = ownerId,
            //            Balance = 0,
            //            Arrears = payment
            //        };
            //        ac.ModifiedLog(staffId, $"操作员{staffName}对业主{ac.Name}进行开户操作");
            //        _repository.Add(ac);
            //        accountId = ac.Id.ToString();
            //    }

            //    //获取水表集合
            //    var meters = _repository.FindAll<Meter>().Where(m => m.OwnerId == owner.Id.ToString()).ToList();
            //    var message = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} ";
            //    message = meters.Aggregate(message, (current, t) => current + $" {t.MeterType}  {t.StepPriceId}");
            //    var refillRecord = new RefillRecord
            //    {
            //        OwnerId = ownerId,
            //        AccountId = accountId,
            //        StaffId = staffId,
            //        LastBalance = lastBalance,
            //        ShouldPayment = payment,
            //        RefillSum = refill,
            //        RefillType = AmountChangedUpMode.充值,
            //        Rescind = 0,
            //        RefillMessage = message
            //    };
            //    //添加充值记录
            //    if (_repository.Add(refillRecord) > 0)
            //    {
            //        //修改金额
            //        var upAcc = _accountRepository;
            //        var account = upAcc.FindAll<Account>().First(o => o.Id.ToString() == accountId);
            //        //实际金额=实收金额+余额-欠款
            //        var value = refill + account.Balance - account.Arrears;
            //        account.Arrears = 0;
            //        account.Balance = value;
            //        upAcc.Update(account);
            //        return true;
            //    }

            //    exception = new Exception("充值失败");
            //    return false;
            //临时增加

             return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = new Exception(e.Message);
                return false;
            }
        }

        /// <summary>
        ///     退费
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="accountId"></param>
        /// <param name="returns"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool ReturnsAccount(string staffId, string ownerId, string accountId, dynamic returns,
            out Exception exception)
        {
            //解析成功--mock
            exception = null;
            using (var _context = Datas.ContextBuilder.Build())
            {
                try
                {
                    //var account = _repository.FindAll<Account>().First(o => o.Id.ToString() == accountId);
                    var orders = _context.OrderDetail.Where(m => m.OwnerId == ownerId);
                    //判断退费与余额大小
                    if (orders.Sum(m=>m.Money) < returns)
                    {
                        exception = new Exception("实际退费大于余额,无法提交");
                        return false;
                    }
                    //添加扣费(退费)记录
                    var orderDetailEntity = new OrderDetail
                    {
                        CostType = 2,
                        Money = -returns,
                        OwnerId = ownerId,
                        RechargeChannels = "平台退费",
                        CreateTime = DateTime.Now
                    };
                    _context.OrderDetail.Add(orderDetailEntity);
                    int count=_context.SaveChanges();
                    if (count > 0) 
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                        //if (count > 0)
                        //{
                        //实际金额=余额-退费
                        //account.Balance -= returns;
                        //context.Accounts.Update(account);
                        //return context.SaveChanges() > 0;
                        //}
                        //exception = new Exception("退费失败");
                        //return false;
                        //临时增加
                     
                }
                catch (Exception e)
                {
                    _logger.Error(e);
                    exception = new Exception(e.Message);
                    return false;
                }
            }
        }

        /// <summary>
        ///     查询扣费信息
        /// </summary>
        /// <param name="payloadId"></param>
        /// <param name="aid"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        /// <param name="ownerId"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public object SelectPayment(string payloadId, string aid, int page, int pageSize, out int count,
            string ownerId, string accountId)
        {
            try
            {
                //    //获取业主信息
                //    var owner = _repository.FindAllAsNoTracking<Owner>().First(o => o.Id.ToString() == ownerId);
                //    var meters = _repository.FindAllAsNoTracking<Meter>().Where(m => m.OwnerId == owner.Id.ToString())
                //        .ToList();
                //    //获取账户信息
                //    var account = _repository.FindAllAsNoTracking<Account>().First(a => a.Id.ToString() == accountId);
                //    //获取扣费记录
                //    var payments = _repository.FindAllAsNoTracking<AmountChangedDownRecord>().Where(p =>
                //            p.OwnerId == ownerId && meters.Select(m => m.MeterNumber).Contains(p.MeterNumber) &&
                //            p.AmountChangedDownMode == AmountChangedDownMode.水费扣费 &&
                //            p.RecordState == RecordStateEnum.Normal)
                //        .ToList();
                //    //获取结算信息
                //    var settlements = _repository.FindAllAsNoTracking<SettlementRecord>().Where(s =>
                //        payments.Select(p => p.SettlementId).Contains(s.Id.ToString())).ToList();
                //    count = payments.Count;
                //    var result = new object[count];
                //    for (var i = 0; i < payments.Count; i++)
                //    {
                //        var payment = payments[i];
                //        var meter = meters.First(m => m.MeterNumber == payment.MeterNumber);
                //        var settlement = settlements.First(s => s.Id.ToString() == payment.SettlementId);
                //        result[i] = new
                //        {
                //            meterType = meter.MeterType, //水表类型
                //            meterNumber = meter.MeterNumber, //水表编号
                //            startTime = settlement.StartTime, //开始时间
                //            endTime = settlement.EndTime, //结束时间
                //            startRead = settlement.StartRead, //起始读数
                //            endRead = settlement.EndTime, //终止时读数
                //            monthAmount = settlement.MeterValue, //用量
                //            unitPrice = settlement.Price1, //每单位水价
                //            cost = payment.PaymentSum,
                //            message = payment.PaymentMessage //业务信息内容      
                //        };
                //    }

                //    //获取分页数据
                //    var pageList = PaginatedList<object>.Create(result.ToList(), page, pageSize);
                //    return pageList;
                //临时增加
                count = 0;
                return new object();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }

        /// <summary>
        ///     查询扣费信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="aid"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="starTime"></param>
        /// <param name="endTime"></param>
        /// <param name="paymentType"></param>
        /// <param name="count"></param>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <param name="ownerId"></param>
        /// <param name="accountId"></param>
        /// <returns></returns>
        public object SelectPayment(string areaId, string aid, int page, int pageSize, DateTime starTime,
            DateTime endTime, int paymentType, out int count,
            string searchType = "", string searchValue = "", string ownerId = "", string accountId = "")
        {
            try
            {
                ////第一步 获取所有用户信息
                //var districtlist = _districtRepository.GetBaseDistrictEntities(areaId, aid);
                ////_repository.FindAllAsNoTracking<DistrictEntity>().ToList();
                ////获取主区域及下所有子区域信息
                ////var districts = _districtLogic.GetDistrictsByUid(payloadId, districtlist);
                ////var districts = districtlist;
                ////if (!string.IsNullOrEmpty(aid)) districts = _districtLogic.DistrictEntitiesById(aid, districtlist);

                ////if (districts.Count == 0)
                ////    districts = districtlist.Where(d => d.Id.ToString() == aid).ToList();
                ////获取业主信息
                //var owners = _repository.FindAllAsNoTracking<Owner>().Where(o =>
                //    districtlist.Select(d => d.Id.ToString()).Contains(o.DistrictId) &&
                //    o.RecordState == RecordStateEnum.Normal).ToList();
                ////条件筛选
                //owners = _baseInfoLogic.QuerySearchOwner(searchType, searchValue, owners);
                ////获取水表信息
                //var meters = _repository.FindAllAsNoTracking<Meter>().Where(m =>
                //        owners.Select(o => o.Id.ToString()).Contains(m.OwnerId) &&
                //        m.RecordState == RecordStateEnum.Normal)
                //    .ToList();
                //meters = _baseInfoLogic.QuerySearchMeter(searchType, searchValue, meters);
                ////获取扣费记录
                //var payments = _repository.FindAllAsNoTracking<AmountChangedDownRecord>().Where(p =>
                //    owners.Select(o => o.Id.ToString()).Contains(p.OwnerId) &&
                //    p.RecordState == RecordStateEnum.Normal).ToList();
                ////水费扣费
                //var paymentsmeter = payments.Where(p => meters.Select(m => m.MeterNumber).Contains(p.MeterNumber) &&
                //                                        p.AmountChangedDownMode == AmountChangedDownMode.水费扣费).ToList();
                ////获取其他扣费记录
                //var paymentOther = payments.Where(p => p.AmountChangedDownMode != AmountChangedDownMode.水费扣费).ToList();
                ////获取结算信息
                //var settlements = _repository.FindAllAsNoTracking<SettlementRecord>().Where(s =>
                //    paymentsmeter.Select(p => p.SettlementId).Contains(s.Id.ToString())).ToList();
                //count = paymentsmeter.Count;
                //var result = new List<object>();
                //if (paymentType == (int)AmountChangedDownMode.水费扣费)
                //{
                //    //获取水费扣费记录
                //    result = (from payment in paymentsmeter
                //              let owner = owners.First(o => o.Id.ToString() == payment.OwnerId)
                //              let meter = meters.First(m => m.MeterNumber == payment.MeterNumber)
                //              let settlement = settlements.First(s => s.Id.ToString() == payment.SettlementId)
                //              select new
                //              {
                //                  ownerId = owner.Id.ToString(), //业主Id                
                //                  ownerName = owner.Name, //业主名称
                //                  houseNumber = owner.HouseNumber, //门牌号               
                //                  meterType = meter.MeterType, //水表类型
                //                  meterNumber = meter.MeterNumber, //水表编号
                //                  startTime = settlement.StartTime, //开始时间
                //                  endTime = settlement.EndTime, //结束时间
                //                  startRead = settlement.StartRead, //起始读数
                //                  endRead = settlement.EndTime, //终止时读数
                //                  monthAmount = settlement.MeterValue, //用量
                //                  unitPrice = settlement.Price1, //每单位水价
                //                  cost = payment.PaymentSum,
                //                  message = payment.PaymentMessage //业务信息内容      
                //              }).Cast<object>()
                //        .ToList();
                //}
                //else
                //{
                //    //其他扣费记录
                //    result = ((from payment in paymentOther
                //               let owner = owners.First(o => o.Id.ToString() == payment.OwnerId)
                //               select new PaymentListItem
                //               {
                //                   ownerId = owner.Id.ToString(), //业主Id                
                //                   ownerName = owner.Name, //业主名称
                //                   houseNumber = owner.HouseNumber, //门牌号 
                //                   mobile = owner.Mobile,
                //                   balance = GetBalance(owner.Id.ToString()),
                //                   paymentType = payment.AmountChangedDownMode.ToString(),
                //                   paymentTypeText =
                //                       Enum.GetName(typeof(AmountChangedDownMode), payment.AmountChangedDownMode),
                //                   cost =
                //                       decimal.ToDouble(Math.Floor(payment.PaymentSum * 100000) /
                //                                        100000), //直接转换会得到错误数据，Math.Floor用于减少decimal小数点后长度，
                //                   message = Enum.GetName(typeof(AmountChangedDownMode), payment.AmountChangedDownMode)
                //               }).Cast<object>().ToList());
                //}
                ////获取分页数据
                //var pageList = PaginatedList<object>.Create(result.ToList(), page, pageSize);
                //return pageList;
                //临时增加
                count = 0;
                return new object();
            }
            catch (Exception e)
            {
                _logger.Error(e);
                throw new Exception($"查询账户信息错误{e.Message}");
            }
        }

        private double GetBalance(string ownerId)
        {
            //var account = _repository.FindAllAsNoTracking<Account>().First(a => a.OwnerId == ownerId);
            //return decimal.ToDouble(Math.Floor(account.Balance * 100000) /
            //                        100000); //直接转换会得到错误数据，Math.Floor用于减少decimal小数点后长度，
            ////return Convert.ToDouble(account.Balance);
            return 0;
        }

        /// <summary>
        ///     费用减免--暂停
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="accountId"></param>
        /// <param name="money"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool FeeDerate(Token token, string userId, string accountId, decimal money, out Exception exception)
        {
            //解析成功--mock
            throw new NotImplementedException("此方法不启用，功能定位不明确");
        }

        /// <summary>
        ///     查询充值记录
        /// </summary>
        /// <param name="payloadId"></param>
        /// <param name="aid"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="count"></param>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        public object SelectRefills(string areaId, string aid, int page, int pageSize, DateTime startTime,
            DateTime endTime, out int count, string searchType, string searchValue)
        {
            try
            {
                //    //第一步 获取所有用户信息
                //    var districtlist = _districtRepository.GetBaseDistrictEntities(areaId, aid);
                //    //    _repository.FindAllAsNoTracking<DistrictEntity>().ToList();
                //    ////获取主区域及下所有子区域信息
                //    //var districts = _districtLogic.GetDistrictsByUid(payloadId, districtlist);
                //    //if (!string.IsNullOrEmpty(aid)) districts = _districtLogic.DistrictEntitiesById(aid, districtlist);

                //    //if (districts.Count == 0)
                //    //    districts = districtlist.Where(d => d.Id.ToString() == aid).ToList();
                //    //获取业主信息
                //    var owners = _repository.FindAllAsNoTracking<Owner>().Where(o =>
                //        districtlist.Select(d => d.Id.ToString()).Contains(o.DistrictId) &&
                //        o.RecordState == RecordStateEnum.Normal).ToList();
                //    //条件筛选
                //    owners = _baseInfoLogic.QuerySearchOwner(searchType, searchValue, owners);
                //    //获取业主下所有缴费记录
                //    var refills = _repository.FindAllAsNoTracking<RefillRecord>().Where(r =>
                //        owners.Select(o => o.Id.ToString()).Contains(r.OwnerId) && r.RefillType == AmountChangedUpMode.充值 &&
                //        r.RecordState == RecordStateEnum.Normal).ToList();
                //    count = refills.Count;
                //    var result = new object[count];
                //    for (var i = 0; i < refills.Count; i++)
                //    {
                //        var refill = refills[i];
                //        var owner = owners.First(o => o.Id.ToString() == refill.OwnerId);
                //        var account = _repository.FindAllAsNoTracking<Account>()
                //            .First(m => m.Id.ToString() == refill.AccountId);
                //        var staff = new Staff("其他");
                //        var staffs = _repository.FindAllAsNoTracking<Staff>()
                //            .Where(s => s.Id.ToString() == refill.StaffId).ToList();
                //        if (staffs.Any())
                //            staff = staffs.First();
                //        var district = districtlist.First(d => owner.DistrictId.Contains(d.Id.ToString()));
                //        result[i] = new
                //        {
                //            districtId = district.Id, //片区Id
                //            districtName = district.Name, //片区名称
                //            ownerId = owner.Id, //业主Id                
                //            ownerName = owner.Name, //业主名称
                //            houseNumber = owner.HouseNumber, //门牌号           
                //            mobile = owner.Mobile, //手机号码
                //            accountId = account.Id.ToString(), //账户id)
                //            refillId = refill.Id.ToString(), //缴费(充值)id
                //            refillCreatTime = refill.CreateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                //            lastBalance = refill.LastBalance, //上次余额
                //            payment = refill.ShouldPayment, //本次应缴(缴费金额-余额)
                //            refill = refill.RefillSum, //本次实缴        
                //            balance = account.Balance, //账户余额
                //            operatorName = staff.Name,
                //            refillstatus = refill.Rescind //记录状态，0 正常，1 已恢复的充值记录,恢复按钮不可用
                //        };
                //    }

                //    //获取分页数据
                //    var pageList = PaginatedList<object>.Create(result.ToList(), page, pageSize);
                //    return pageList;
                //临时增加
                count = 0;
                return new object();
            }
            catch (Exception e)
            {
                throw new Exception($"查询充值记录错误{e.Message}");
            }
        }

        /// <summary>
        ///     撤销充值缴费记录
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="accountId"></param>
        /// <param name="refillId"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        public bool RevertRefill(string staffId, string ownerId, string accountId, string refillId,
            out Exception exception)
        {
            //解析成功
            exception = null;


            //添加扣费信息
            try
            {
            //    var refillRep = _refillRepository;
            //    var accountRep = _accountRepository;
            //    //获取记录信息
            //    var refill = refillRep.FindAll<RefillRecord>().First(o => o.Id.ToString() == refillId);
            //    //获取账户信息
            //    var account = accountRep.FindAll<Account>().First(o => o.Id.ToString() == accountId);
            //    //修改记录状态
            //    refill.Rescind = 1;
            //    if (refillRep.Update(refill) <= 0)
            //    {
            //        exception = new Exception("撤销充值失败");
            //        return false;
            //    }

            //    //添加扣费(退费)记录
            //    var pay = new AmountChangedDownRecord
            //    {
            //        OwnerId = ownerId,
            //        AccountId = accountId,
            //        MeterNumber = "",
            //        StaffId = staffId,
            //        AmountChangedDownMode = AmountChangedDownMode.撤销充值,
            //        PaymentSum = refill.RefillSum
            //    };
            //    if (_repository.Add(pay) > 0)
            //    {
            //        //实际金额=余额-充值金额
            //        if (account.Balance >= refill.RefillSum)
            //        {
            //            account.Balance = account.Balance - refill.RefillSum;
            //        }
            //        else
            //        {
            //            account.Balance = 0;
            //            account.Arrears += refill.RefillSum - account.Balance;
            //        }

            //        accountRep.Update(account);
                //    return true;
                //}

                //exception = new Exception("撤销充值失败");
                return false;
            }
            catch (Exception e)
            {
                _logger.Error(e);
                exception = new Exception(e.Message);
                return false;
            }
        }

        /// <summary>
        /// 销户操作
        /// </summary>
        /// <param name="token"></param>
        /// <param name="userId"></param>
        /// <param name="accountId"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public bool ClosingAccount(string staffId, string staffName, string ownerId, string accountId, out string message)
        {
            //message = "";
            ////获取账户类型
            //var account = _repository.FindAll<Account>().First(a =>
            //    a.Id.ToString() == accountId && a.RecordState == RecordStateEnum.Normal);
            ////获取水表数据
            //var meters = _repository.FindAllAsNoTracking<Meter>().Where(m =>
            //    m.OwnerId == account.OwnerId && m.RecordState == RecordStateEnum.Normal);
            //var meterNumbers = meters.Select(m => m.MeterNumber).ToList();
            ////所有抄表记录是否结算
            //var meterReadingRecord = _repository.FindAllAsNoTracking<MeterReadingRecord>().Where(m =>
            //    meterNumbers.Contains(m.Number) && m.CloseState == CloseState.UnCLose &&
            //    m.RecordState == RecordStateEnum.Normal);
            //var recordCount = meterReadingRecord.Count();
            ////未结算-无法销户
            //if (recordCount > 0)
            //{
            //    message = $"有{recordCount}条未结算数据,无法销户";
            //    return false;
            //}
            ////结算-下一步
            //if (account.Arrears > 0)
            //{
            //    message = $"欠费{account.Arrears}元,无法销户";
            //    return false;
            //}
            //if (account.Balance > 0)
            //{
            //    message = $"账户有余额{account.Balance}元,无法销户";
            //    return false;
            //}
            ////销户
            //account.RecordState = RecordStateEnum.Deleted;
            //account.ModifiedLog(staffId, $"{staffName}执行销户操作");
            message = "";
            return true;
        }
    }
}